<template>
  <div id='createteam'>
    <div>
      <view-box ref="viewBox" style="height:100vh">
        <div id="x-header">

          <x-header slot="header" :left-options="{backText: ''}" style="width:100%;position:absolute;left:0;top:0;z-index:100;" :title="'创建团队'" :transition="headerTransition" @on-click-more="onClickMore">
            <a href="./#/racelist" style="font-size:24px" slot="right">
              <i class="fa fa-home fa-fw"></i>
            </a>

          </x-header>

        </div>

        <group style="padding-top:50px">
          <x-input v-model="teamName" title="团队名称" placeholder="请填写团队名称" novalidate :show-clear="false" placeholder-align="left"></x-input>
          <!-- <x-textarea  v-model="teamContent" title="团队简介" :max="100" show-counter placeholder="这是团队简介"  ></x-textarea> -->
          <x-textarea v-model="teamContent" title="团队简介" show-counter placeholder="请填写团队简介"></x-textarea>
          <div class="vue-uploader">
            <p style="color: black;padding-left:15px;font-size: 17px">团队封面

              <!-- <span >{{placeholder}}</span> -->

            </p>
            <div v-if='files.length==0' class="file-list">
              <section v-for="(file, index) in files" class="file-item draggable-item">
                <img :src="file.src" alt="" ondragstart="return false;" @click="show(index)">
                <!--<p class="file-name">{{file.name}}</p>-->
                <span class="file-remove" @click="remove(index)">+</span>
              </section>
              <section @click="add($event)" v-if="status == 'ready'" class="file-item needsclick">
                <div class="add needsclick">
                  <span class="needsclick">+</span>
                </div>
              </section>
            </div>

            <div v-if='files.length>0' class="file-list">
              <section v-for="(file, index) in files" class="file-item draggable-item">
                <img :src="file.src" alt="" ondragstart="return false;" @click="show(index)">
                <!--<p class="file-name">{{file.name}}</p>-->
                <span class="file-remove" @click="remove(index)">+</span>
              </section>
              <section @click="add($event)" v-if="status == 'ready'" class="file-item needsclick">
                <div class="add needsclick">
                  <span class="needsclick">更换</span>
                </div>
              </section>
            </div>

            <!--    <section v-if="files.length != 0" class="upload-func">
          <div class="progress-bar">
            <section v-if="uploading" :width="(percent * 100) + '%'">{{(percent * 100) + '%'}}</section>
          </div>
          <div class="operation-box">
            <button v-if="status == 'ready'" @click="submit">上传</button>
            <button v-if="status == 'finished'" @click="finished">完成</button>
          </div>
        </section>-->

            <input type="file" @change="fileChanged" ref="file">
            <div>
              <img style="display:none" class="previewer-demo-img" v-for="(item, index) in list" :src="item.src" width="100" @click="show(index)">
              <div v-transfer-dom>
                <!-- <previewer :list="list" ref="previewer" :options="options"></previewer> -->
              </div>
            </div>

          </div>

          <x-input v-model="teamPasswd" title="入团口令" placeholder="不填写代表接受自由入团" novalidate :show-clear="false" placeholder-align="left"></x-input>

          <!-- <x-button type="primary" @click.native="postCreate()">下一步</x-button> -->

        </group>


        <div v-if='pageType=="baoming"' id='x-bottom'>
          <x-header slot="header" style="width:100%;position:absolute;left:0;bottom:0;z-index:100;" title="">
            <span slot="overwrite-left">
            </span>
            <div @click='postCreate' style="font-size:18px" slot="right">
              <a>下一步</a>
            </div>
          </x-header>
        </div>

        <div v-if='pageType!="baoming"' id='x-bottom'>
          <x-header slot="header" style="width:100%;position:absolute;left:0;bottom:0;z-index:100;" title="">
            <span slot="overwrite-left">
            </span>

            <div @click='postCreate' style="font-size:18px" slot="right">
              <a>下一步</a>
            </div>

          </x-header>
        </div>

      </view-box>

      <!-- <loading :show='showLoading'></loading>-->
    </div>
  </div>

</template>

<script type="text/ecmascript-6">
/* eslint-disable*/

import { TransferDom } from "vux";
import Vue from "vue";
import Myheader from "@/common/components/myheader.vue";
import Myflow from "@/common/components/myflow.vue";
import Loading from "@/common/components/loading.vue";
import Upfile from "@/common/components/upfile.vue";
import Tel from "@/common/components/tel.vue";
import Myaddress from "@/common/components/address.vue";
import MyFooter from "@/common/components/myfooter.vue";

import { cityData } from "@/common/locales/cityData.js";
import { countryData } from "@/common/locales/countryData1.js";

import { enCountryData } from "@/common/locales/enCountryData1.js";
import { pcCountryData } from "@/common/locales/pcCountryData1.js";
import { pcenCountryData } from "@/common/locales/pcenCountryData1.js";
import mixin from "@/common/js/mixin";
import { DatePicker, Cascader } from "element-ui";
Vue.use(DatePicker);
Vue.use(Cascader);

import {
  XHeader,
  Selector,
  Msg,
  Group,
  Cell,
  XButton,
  XInput,
  Datetime,
  PopupRadio,
  ToastPlugin,
  Scroller,
  XNumber,
  XTextarea,
  Checklist,
  XAddress,
  Divider,
  GroupTitle,
  Previewer,
  PopupPicker,
  CellFormPreview,
  ViewBox,
  cookie
} from "vux";

// 获取表单数据
import { getForm } from "@/api/getForm.js";
import { sendForm } from "@/api/sendForm.js";
import { sendPay } from "@/api/sendPay.js";
let srclist = [];
import { postImage } from "@/api/postImage.js";
//axios
import qs from "qs";
import { axios } from "@/api/axios.js";
import { indexedDB } from "@/api/indexedDB.js";
import { setTitle } from "@/common/js/main.js";

//let clock1 = 1

Vue.use(ToastPlugin);

export default {
  mixins: [mixin],
  props: ["page", "host"],
  data() {
    return {
      eventId: "", //项目id
      teamName: "",
      teamPasswd: "",
      teamIcon: "",
      teamContent: "",
      src: `${window.host}stor/base64`,
      status: "ready",
      files: [],
      point: {},
      uploading: false,
      percent: 0,
      srcList: [],
      options: {
        getThumbBoundsFn(index) {
          // find thumbnail element
          let thumbnail = document.querySelectorAll(".previewer-demo-img")[
            index
          ];
          // get window scroll Y
          let pageYScroll =
            window.pageYOffset || document.documentElement.scrollTop;
          // optionally get horizontal scroll
          // get position of element relative to viewport
          let rect = thumbnail.getBoundingClientRect();
          // w = width
          return { x: rect.left, y: rect.top + pageYScroll, w: rect.width };
          // Good guide on how to get element coordinates:
          // http://javascript.info/tutorial/coordinates
        }
      }
    };
  },
  computed: {
    list: function() {
      let array = [];
      this.srcList.forEach(function(item, index) {
        array.push({ src: "//img.ihuipao.cn/" + item });
      });
      return array;
    },
    headerTransition() {
      if (!this.direction) return "";
      return this.direction === "forward"
        ? "vux-header-fade-in-right"
        : "vux-header-fade-in-left";
    }
  },
  beforeCreate() {
    let _this = this;
    setTitle("创建团队");

    // indexedDB("eventId", "get", this.RACEID, "", function(a) {
    //   _this.eventId = a;
    // });
  },
  created() {
    let _this = this;
    this.eventId = window.localStorage.getItem("eventId");
  },
  methods: {
    onClickMore() {},
    postCreate() {
      let _this = this;

      //团队封面
      if (typeof this.files[0] == "undefined") {
        _this.$vux.toast.show({
          type: "warn",
          text: "团队封面未上传",
          onHide() {}
        });
        return;
      } else {
        this.teamIcon = this.files[0].src;
      }

      if (this.teamName == "") {
        _this.$vux.toast.show({
          type: "warn",
          text: "团队名称未填写",
          onHide() {}
        });
        return;
      } else if (this.teamContent == "") {
        _this.$vux.toast.show({
          type: "warn",
          text: "团队简介未填写",
          onHide() {}
        });
        return;
      }
      //teamName: "",
      //teamPasswd: "",
      //teamIcon: "",
      //teamContent: "",
      //
      //
      //
      //

      this.axios
        .post(
          `${window.host}team/create`,
          qs.stringify({
            name: this.teamName,
            eventid: this.eventId,
            passwd: this.teamPasswd,
            icon: this.teamIcon,
            content: this.teamContent
          })
        )
        .then(
          response => {
            if (response.data.code == "200") {
              window.localStorage.setItem("teamId", response.data.data.id);
              window.localStorage.setItem("passwd", _this.teamPasswd);
              _this.$router.push("/certificate/identity");
              // indexedDB(
              //   "teamId",
              //   "set",
              //   this.RACEID,
              //   response.data.data.id,
              //   function() {
              //     indexedDB(
              //       "passwd",
              //       "set",
              //       _this.RACEID,
              //       _this.teamPasswd,
              //       function() {
              //         _this.$router.push("/disclaimer");
              //       }
              //     );
              //   }
              // );
            } else {
              _this.$vux.toast.show({
                type: "warn",
                text: response.data.msg,
                onHide() {}
              });
            }
          },
          error => {
            console.log(error);
            _this.$vux.toast.show({
              type: "warn",
              text: res.msg,
              onHide() {}
            });
          }
        );
    },
    remove(index) {
      this.files.splice(index, 1);
      this.srcList.splice(index, 1);
      //srclist.splice(index, 1)
    },
    show(index) {
      this.$refs.previewer.show(index);
    },
    add(e) {
      this.$refs.file.click();
    },
    submit() {
      if (this.files.length === 0) {
        //console.warn('没有上传的文件')
        return;
      }

      const formData = new FormData();
      this.files.forEach(item => {
        formData.append(item.name, item.file);
      });
      const xhr = new XMLHttpRequest();
      xhr.upload.addEventListener("progress", this.uploadProgress, false);
      xhr.open("POST", this.src, true);
      this.uploading = true;
      xhr.send(formData);
      xhr.onload = () => {
        this.uploading = false;
        if (xhr.status === 200 || xhr.status === 304) {
          this.status = "finished";
          //console.log('upload success!')
        } else {
          //console.log(`error：error code ${xhr.status}`)
        }
      };
    },
    fileChanged() {
      const list = this.$refs.file.files;
      for (let i = 0; i < list.length; i++) {
        if (!this.isContain(list[i])) {
          const item = {
            name: list[i].name,
            size: list[i].size,
            file: list[i]
          };
          this.html5Reader(list[i], item);
          this.files[0] = item;
        }
      }

      this.$refs.file.value = "";
      //把文件数据传递给父组件
    },
    // 将图片文件转成BASE64格式
    html5Reader(file, item) {
      const reader = new FileReader();
      reader.onload = e => {
        //this.srcList.push(e.target.result)
        //this.$set(item, 'src', e.target.result)

        this.$vux.loading.show({
          text: "图片上传中"
        });
        postImage(this.src, {
          key: "file",
          file: e.target.result
        }).then(response => {
          this.$vux.loading.hide();
          if (response.data.code == "200") {
            srclist.push(response.data.data.path);
            this.srcList.push(response.data.data.path);
            this.$set(
              item,
              "src",
              "//img.ihuipao.cn/" + response.data.data.path
            );
            // console.log(srclist)
            // console.log(this.srcList)
            // console.log(this.srcList[0])
            this.$emit("fileChange", {
              files: this.srcList,
              index: this.index
            });
          } else {
            this.$vux.toast.show({
              type: "warn",
              text: response.data.msg
            });
          }
        });
      };
      reader.readAsDataURL(file);
    },
    isContain(file) {
      for (let i = 0; i < this.files.length; i++) {
        if (
          this.files[i].name === file.name &&
          this.files[i].size === file.size
        ) {
          this.$vux.toast.show({
            type: "warn",
            text: "不能上传重复的文件"
          });
          return true;
        }
      }
      return false;
    },
    uploadProgress(evt) {
      const component = this;
      if (evt.lengthComputable) {
        const percentComplete = Math.round(evt.loaded * 100 / evt.total);
        component.percent = percentComplete / 100;
      } else {
        //console.warn('upload progress unable to compute')
      }
    }
  },
  directives: {
    TransferDom
  },
  components: {
    XHeader,
    Tel,
    Divider,
    Myheader,
    Myflow,
    Group,
    Cell,
    XButton,
    XInput,
    Datetime,
    PopupRadio,
    ToastPlugin,
    Scroller,
    XNumber,
    XTextarea,
    Checklist,
    XAddress,
    Loading,
    Upfile,
    GroupTitle,
    Msg,
    Selector,
    PopupPicker,
    CellFormPreview,
    MyFooter,
    ViewBox,
    Myaddress
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" rel="stylesheet/less">
.vue-uploader {
  border: 1px solid #e5e5e5;
  padding-top: 10px;
}

.vue-uploader .file-list {
  padding: 10px 15px;
}

.vue-uploader .file-list:after {
  content: "";
  display: block;
  clear: both;
  visibility: hidden;
  line-height: 0;
  height: 0;
  font-size: 0;
}

.vue-uploader .file-list .file-item {
  float: left;
  position: relative;
  width: 100px;
  text-align: center;
}

.vue-uploader .file-list .file-item img {
  width: 80px;
  height: 80px;
  border: 1px solid #ececec;
}

.vue-uploader .file-list .file-item .file-remove {
  position: absolute;
  right: 12px;
  display: block;
  top: 4px;
  width: 20px;
  height: 20px;
  color: white;
  cursor: pointer;
  line-height: 15px;
  border-radius: 100%;
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
  background: rgba(0, 0, 0, 0.5);
  font-size: 20px;
}

.vue-uploader .file-list .file-item:hover .file-remove {
  display: inline;
}

.vue-uploader .file-list .file-item .file-name {
  margin: 0;
  height: 40px;
  word-break: break-all;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.vue-uploader .add {
  width: 80px;
  height: 80px;
  margin-left: 10px;
  float: left;
  text-align: center;
  line-height: 80px;
  border: 1px dashed #ececec;
  font-size: 30px;
  cursor: pointer;
}

.vue-uploader .upload-func {
  display: flex;
  padding: 10px;
  margin: 0px;
  background: #f8f8f8;
  border-top: 1px solid #ececec;
}

.vue-uploader .upload-func .progress-bar {
  flex-grow: 1;
}

.vue-uploader .upload-func .progress-bar section {
  margin-top: 5px;
  background: #00b4aa;
  border-radius: 3px;
  text-align: center;
  color: #fff;
  font-size: 12px;
  transition: all 0.5s ease;
}

.vue-uploader .upload-func .operation-box {
  flex-grow: 0;
  padding-left: 10px;
}

.vue-uploader .upload-func .operation-box button {
  padding: 4px 12px;
  color: #fff;
  background: #007acc;
  border: none;
  border-radius: 2px;
  cursor: pointer;
}

.vue-uploader > input[type="file"] {
  display: none;
}

#form .button-wrapper {
  margin-top: 30px;
  margin-bottom: 30px;
}

.vue-uploader .required {
  display: inline-block;
  color: #f43530;
}

#form .norequired {
  display: none;
}

#form .required {
  display: inline-block;
  color: #f43530;
}

#form #popup-radio-warpper .group-title {
  position: relative;
  top: 20px;
  z-index: 9;
  height: 0;
  color: #000;
  font-size: 17px;
  pointer-events: none;
}

#form #popup-radio-warpper .weui-cell {
  height: 24px;
}

#form #number-warpper .group-title {
  position: relative;
  top: 20px;
  z-index: 9;
  height: 0;
  color: #000;
  font-size: 17px;
}

#form #number-warpper .weui-cell {
  height: 24px;
}

.msg .weui-msg__desc p {
  line-height: 1.5;
}

#form .mask {
  width: 100%;
  height: 100vh;
  background: red;
  position: absolute;
}

#form .tel .vux-x-input {
  padding: 0;
}

#form .tel .weui-select {
  width: 105px;
  box-sizing: border-box;
}

#form .tel .weui-cell__primary {
  padding-left: 15px;
}

#form .tel .vux-x-input .vux-selector:after {
  content: " ";
  position: absolute;
  right: 0;
  top: 0;
  width: 1px;
  bottom: 0;
  border-right: 1px solid #e5e5e5;
  color: #e5e5e5;
  -webkit-transform-origin: 100% 0;
  transform-origin: 100% 0;
  -webkit-transform: scaleX(0.5);
  transform: scaleX(0.5);
}

#msg .weui-cell {
  text-align: left;
}

#msg .weui-msg__text-area {
  padding: 0;
}

.pc_date_select select {
  background-color: #ffffff;
  background-image: none !important;
  filter: none !important;
  border: 1px solid #e5e5e5;
  outline: none;
  width: 100px;
  height: 25px;
  line-height: 25px;
}

.pc_address_select select {
  background-color: #ffffff;
  background-image: none !important;
  filter: none !important;
  border: 1px solid #e5e5e5;
  outline: none;
  width: 180px;
  height: 25px;
  line-height: 25px;
}

.pc_country_select .weui-cell_select-after .weui-select {
  padding-left: 15px;
}

#form .weui-cells__title {
  color: #000;
}
</style>
<style type="text/css">
#createteam .weui-cells {
  margin-top: 0;
}
</style>



